package com.btc.watcher;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONObject;

public class WatcherWidgetProvider extends AppWidgetProvider {

    /**
     * This constant is what we send to ourself to force a refresh
     */
    public static final String REFRESH="com.btc.watcher.REFRESH";

    /**
     *  All our notifications will have this id
     */
    public static final int BITCOIN_NOTIFY_ID = 1;


    /**
     * When we recieve an Intent, we will either force a refresh if it matches
     *  REFRESH, or pass it on to our superclass
     */
    @Override
    public void onReceive(Context ctxt, Intent intent) {

        if (REFRESH.equals(intent.getAction())) {
            //createNotification(ctxt, R.drawable.bitcoin, "Recieved Update", "It equals REFRESH", "onRecieved");
            ctxt.startService(new Intent(ctxt, UpdateService.class));
        }
        else {
            super.onReceive(ctxt, intent);
        }
    }

    /**
     * createNotification creates a notification which stays in the notification bar till removed
     * @param Context ctxt
     * @param icon (such as R.drawable.bitcoin)
     * @param tickerText (notification ticker)
     * @param contentTitle (title of notification)
     * @param contentText (details of notification)
     */
    private static void createNotification(Context ctxt, int icon, CharSequence tickerText, CharSequence contentTitle, CharSequence contentText) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) ctxt.getSystemService(ns);
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, tickerText, when);


        Intent notificationIntent = new Intent(ctxt, WatcherWidgetProvider.class);
        PendingIntent contentIntent = PendingIntent.getActivity(ctxt, 0, notificationIntent, 0);

        notification.setLatestEventInfo(ctxt, contentTitle, contentText, contentIntent);


        mNotificationManager.notify(BITCOIN_NOTIFY_ID, notification);
    }

    /**
     * createNotification creates a notification which only briefly appears in the ticker bar
     * @param Context ctxt
     * @param icon (such as R.drawable.bitcoin)
     * @param tickerText (notification ticker)
     */
    private static void createTicker(Context ctxt, int icon, CharSequence tickerText) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) ctxt.getSystemService(ns);
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, tickerText, when);

        Intent notificationIntent = new Intent(ctxt, WatcherWidgetProvider.class);
        PendingIntent contentIntent = PendingIntent.getActivity(ctxt, 0, notificationIntent, 0);

        notification.setLatestEventInfo(ctxt, null, null, contentIntent);

        mNotificationManager.notify(BITCOIN_NOTIFY_ID, notification);
        mNotificationManager.cancel(BITCOIN_NOTIFY_ID);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        //createNotification(context, R.drawable.bitcoin, "Recieved Update", "It equals REFRESH", "onUpdate");
        context.startService(new Intent(context, UpdateService.class));
    }
    public static class UpdateService extends IntentService {

        public UpdateService() {
            super("WatcherWidgetProvider$UpdateService");
        }

        @Override
        public void onCreate() {
            super.onCreate();


        }

        @Override
        public void onHandleIntent(Intent intent) {
            //createNotification(getApplicationContext(), R.drawable.bitcoin, "Recieved Intent", "Handling it now", "onHandleIntent");
            ComponentName me = new ComponentName(this, WatcherWidgetProvider.class);
            AppWidgetManager awm = AppWidgetManager.getInstance(this);
            awm.updateAppWidget(me, buildUpdate(this));
        }

        private RemoteViews buildUpdate(Context context) {

            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.watcher_appwidget);
            // Create an Intent to launch ExampleActivity

            /*Uri uri = Uri.parse("http://mtgox.com/");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            */
            Intent intent = new Intent(this, WatcherWidgetProvider.class);
            intent.setAction(REFRESH);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

            // Get the layout for the App Widget and attach an on-click listener to the button
            views.setOnClickPendingIntent(R.id.bitcoinButton, pendingIntent);

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://www.mtgox.com/code/data/ticker.php");
            try {
                HttpResponse response = client.execute(post);

                InputStream is = response.getEntity().getContent();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(20);

                //convert byte array to string
                int current = 0;
                while((current = bis.read()) != -1) {
                    baf.append((byte)current);
                }
                String text = new String(baf.toByteArray());
                JSONObject jObject = new JSONObject(text);
                JSONObject jTicker = jObject.getJSONObject("ticker");


                //highText.setText("High: " + jTicker.getString("high"));
                //lowText.setText("Low: " + jTicker.getString("low"));
                views.setTextViewText(R.id.widgetVolText,"Vol: " + jTicker.getString("vol"));
                views.setTextViewText(R.id.widgetBuyText,"Bid: $" + jTicker.getString("buy"));
                views.setTextViewText(R.id.widgetSellText,"Ask: $" + jTicker.getString("sell"));
                views.setTextViewText(R.id.widgetLowText,"Low: $" + jTicker.getString("low"));
                views.setTextViewText(R.id.widgetHighText,"High: $" + jTicker.getString("high"));
                views.setTextViewText(R.id.widgetLastText,"Last: $" + jTicker.getString("last"));

                //Date date = new Date();
                //DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US);
                //String currentTime = df.format(date);
                SimpleDateFormat sdf = new SimpleDateFormat("h:mm a", Locale.US);
                String currentTime = sdf.format(new Date());
                views.setTextViewText(R.id.label,"\nUpdated: " + currentTime);

                createTicker(context, R.drawable.bitcoin, "Updated!");

                //lastText.setText("Last: " + jTicker.getString("last"));
                //tv.setText("Bitcoin stats retrieved from Mt Gox:");



            } catch(Exception e) {
                e.printStackTrace();
                //tv.setText(getStackTrace(e));
                //views.setTextViewText(R.id.widgetBuyText,"Error retrieving data from Mt. Gox.");
                SimpleDateFormat sdf = new SimpleDateFormat("h:mm a", Locale.US);
                String currentTime = sdf.format(new Date());
                //views.setTextViewText(R.id.label,"Make sure you have cell or internet reception. Last attempted at " + currentTime);
                createNotification(context, R.drawable.bitcoin, "Update was not successful!", "Update not successful", "No cell or internet connection to server, try again");
            }

            // Tell the AppWidgetManager to perform an update on the current App Widget
            return views;
        }

        private String getStackTrace(Exception t)
        {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw, true);
            t.printStackTrace(pw);
            pw.flush();
            sw.flush();
            return sw.toString();
        }
    }




}
